<?php

class BaseModel {
	
	protected $columnTypes;
	
	public function __set( $propriedade, $valor )
	{
	    if ( !is_bool( $valor ) AND $valor !== NULL ){
		    $valor = TUtils::toMaiusculas( $valor );
	    }
	    $this->$propriedade = $valor; 
	}
	
	public function __get( $propriedade )
	{
		return $this->$propriedade;
	}
	
	public function getTableName()
	{
		$class = get_class($this);
		return constant("{$class}::tablename");
	}
	
	public function getTableKey()
	{
		$class = get_class($this);
		return constant("{$class}::tablekey");
	}
	
	public function getTableSequence(){
		$class = get_class($this);
		return constant("{$class}::tablesequence");	
	}
	
	public function getTableKeyValue()
	{
		$tablekey = $this->getTableKey();
		return $this->$tablekey;
	}
	
	public function setTableKeyValue( $value )
	{
		$tablekey = $this->getTableKey();
		$this->$tablekey = $value;
	}
	
	public function getAttributeSQLValue( $field, $value ){
		
		if ( $value !== false && $value === NULL )
			$value = "NULL";
			
		if ( strpos( $this->columnTypes[ $field ], 'bool' ) > -1 && $value !== "NULL" )
			if ( $value === true OR $value === 't' )
				$value = 't';
			else
				$value = 'f';
				
		if ( $value != "NULL" ){

			if ( strpos( $this->columnTypes[ $field ], 'varchar' ) > -1 OR 
				 strpos( $this->columnTypes[ $field ], 'bool' ) > -1  OR
				 strpos( $this->columnTypes[ $field ], 'date' ) > -1 OR
				 strpos( $this->columnTypes[ $field ], 'text' ) > -1 OR 
				 strpos( $this->columnTypes[ $field ], 'timestamp' ) > -1 
				)
				$value = "'$value'";
		}
		
		return $value;
		
	}
	
	public function __construct( $objetoid = null )
	{
        $class = get_class($this);
        
        if (is_numeric ($objetoid))
        	$sql = "SELECT * FROM " . self::getTableName() . " WHERE " . self::getTableKey() ." = $objetoid;";
		else 
    	   $sql = "SELECT * FROM " . self::getTableName() . " LIMIT 1";
    	   
        $result = TUtils::CriarResultSet($sql);
		
        $numcam = pg_num_fields($result);
        $campos = pg_fetch_object($result);
            
        if ( pg_num_rows($result) > 0 && is_numeric ( $objetoid ) )
            for ($i = 0 ; $i < $numcam ; $i++) {
        		$nomecampo = pg_field_name($result, $i);
            	$nomecamposet = pg_field_name($result, $i);
            	$this->$nomecamposet = $campos->$nomecampo;
        	}
        
        for ( $i = 0; $i < $numcam; $i++ )
        	$this->columnTypes[pg_field_name( $result, $i )] = pg_field_type( $result, $i );
            
    }
    
	public function listar( $criterio = null )
    {
    	return TSqlSelect::simpleSelect( self::getTableName(), self::getTableKey(), $criterio );
    }

    public function excluir()
    {
    	if ($this->getTableKeyValue()) {
    		$sql = "DELETE FROM " . self::getTableName() . " WHERE " . self::getTableKey() . " = " . $this->getTableKeyValue();
    		pg_query(conexao::Conectar(), $sql) or die ("Erro ao excluir.");
    	}
    }
    
	public function excluirGrupo( $ids )
    {
    	$sql = "DELETE FROM " . self::getTableName() . " WHERE " . self::getTableKey() . " in (";
        for($i = 0; $i < count($ids); $i++)
        {
        	$sql .= $ids[$i];
            if ($i < count($ids)-1) {
            	$sql .= ",";
            }
        }
        $sql .= ")";
        
        pg_query(conexao::Conectar(), $sql) or die ("Erro ao excluir.");
    }
    
    public function getData()
    {
    	$data = get_object_vars( $this );
    	
    	//Não retorna os arrays
    	foreach ($data as $key=>$value) {
    		if (is_array($value)) {
    			unset($data[$key]);
    		}
    	}
    	
    	return $data;
    }
    
    public function salvar()
    {
    	if ($this->getTableKeyValue() === NULL) {
    		$this->inserir();
    	}
    	else {
    		$classe = get_class( $this );
    		$temp = new $classe( $this->getTableKeyValue() );
    		if ( $temp->getTableKeyValue() === NULL )
    			$this->inserir();
    		else 
   				$this->alterar();
    	}
    }
    
    public function alterar()
    {
    	
    	$sql = "UPDATE " . $this->getTableName() . " SET ";
    	
    	$i = 0;
    	foreach ( $this->getData() as $key => $value ){
    		if ( ++$i > 1  ) $sql .= ", ";
    		$sql .= $key . " = " . $this->getAttributeSQLValue( $key, $value );
    	}
    	
    	$sql .= " WHERE " . $this->getTableKey() . " = " . $this->getTableKeyValue();
    	
    	pg_query(conexao::Conectar(), $sql);
    	
    }
    
    public function inserir()
    {
    	
    	$data = $this->getData();	
    	
    	$sql = "INSERT INTO " . $this->getTableName() . " ( ";
    	
    	$i = 0;
    	foreach ( $data as $key=>$value ){
    		if ( $key != $this->getTableKey() OR ( $value != NULL AND $value != '' ) ){
    			if ( ++$i > 1  ) $sql .= ", ";
    			$sql .= $key;
    		}
    	}
    	
    	$sql .= " ) VALUES ( ";
    	
    	$i = 0;
    	foreach ( $data as $key=>$value ){
    		if ( $key != $this->getTableKey() OR ( $value != NULL AND $value != '' ) ){
    			if ( ++$i > 1  ) $sql .= ", ";
    			$sql .= $this->getAttributeSQLValue( $key, $value );
    		}
    	}

    	$sql .= ")";
    	
    	pg_query(conexao::Conectar(), $sql);
    	
    	$r = pg_fetch_object(TUtils::CriarResultSet("select last_value from " . $this->getTableSequence() ), 0 );
    	$this->setTableKeyValue( $r->last_value );
    	
    }
}